<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="图片上传问题正在参与的项目由于要求原因，所有的图片引入、存储均修改成base64的格式来进行，这里当时我负责图片下载部分的处理逻辑。上传图片时，用FormData的方式和表单一起来上传，由后端来分析并处理图片的base64格式，并存储在服务器静态资源路径下，数据库中保存存放地址路径。在前端获取图片时，则用axios发起ajax请求，异步获取base64格式的图片数据，再转换成图片显示，其实关键在于">
<meta property="og:type" content="article">
<meta property="og:title" content="图片上传问题">
<meta property="og:url" content="http://example.com/2021/07/14/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E5%9B%BE%E7%89%87%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%A4%84%E7%90%86/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="图片上传问题正在参与的项目由于要求原因，所有的图片引入、存储均修改成base64的格式来进行，这里当时我负责图片下载部分的处理逻辑。上传图片时，用FormData的方式和表单一起来上传，由后端来分析并处理图片的base64格式，并存储在服务器静态资源路径下，数据库中保存存放地址路径。在前端获取图片时，则用axios发起ajax请求，异步获取base64格式的图片数据，再转换成图片显示，其实关键在于">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-07-14T13:28:16.000Z">
<meta property="article:modified_time" content="2021-11-03T08:32:40.640Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="学校项目应用">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/07/14/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E5%9B%BE%E7%89%87%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%A4%84%E7%90%86/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>图片上传问题 | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/07/14/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E5%9B%BE%E7%89%87%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%A4%84%E7%90%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          图片上传问题
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-07-14 21:28:16" itemprop="dateCreated datePublished" datetime="2021-07-14T21:28:16+08:00">2021-07-14</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:32:40" itemprop="dateModified" datetime="2021-11-03T16:32:40+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/" itemprop="url" rel="index"><span itemprop="name">学校项目应用</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="图片上传问题"><a href="#图片上传问题" class="headerlink" title="图片上传问题"></a>图片上传问题</h1><p>正在参与的项目由于要求原因，所有的图片引入、存储均修改成base64的格式来进行，这里当时我负责图片下载部分的处理逻辑。上传图片时，用FormData的方式和表单一起来上传，由后端来分析并处理图片的base64格式，并存储在服务器静态资源路径下，数据库中保存存放地址路径。在前端获取图片时，则用axios发起ajax请求，异步获取base64格式的图片数据，再转换成图片显示，其实关键在于将base64转译成blob对象。</p>
<h2 id="文件格式类型"><a href="#文件格式类型" class="headerlink" title="文件格式类型"></a>文件格式类型</h2><p>Blob、ArrayBuffer、File可以归为一类，它们都是数据；FileReader算是一种工具，用来读取数据；FormData则可以看做是一个应用数据的场景。</p>
<h3 id="Blob"><a href="#Blob" class="headerlink" title="Blob"></a>Blob</h3><p>blob:全称是binary large object,二进制大文件对象，非Javascript特有，计算机通用对象。MDN上解释是，一个Blob对象就是一个包含有只读原始数据的类文件对象，通俗讲就是不可修改的二进制文件。一般我们通过构造函数创建Blob对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> aBlob = <span class="keyword">new</span> Blob( array, options );</span><br><span class="line"><span class="comment">/*array：一堆数据构成的数组 options：设置一些属性，主要是type属性	</span></span><br><span class="line"><span class="comment">Blob对象的属性:</span></span><br><span class="line"><span class="comment">size:数据的字节大小（只读）</span></span><br><span class="line"><span class="comment">type:数据的MIME类型，例如'image/jpeg'（只读）</span></span><br><span class="line"><span class="comment">(MIME:描述消息内容类型的因特网标准)</span></span><br><span class="line"><span class="comment">Blob对象只有slice方法，对文件分割</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">aBlob.slice(start, end ,contentType)</span><br></pre></td></tr></table></figure>

<h3 id="File"><a href="#File" class="headerlink" title="File"></a>File</h3><p>File:File就是文件，继承自Blob，也是二进制对象，也有自己特有的属性和方法，通常用在<input type="file">选择的FileList对象，或者是使用拖拽操作产生的的DataTransfer对象。下面我们用构造函数构建File对象：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myFile = <span class="keyword">new</span> File(array, name,options);</span><br><span class="line"><span class="comment">/* array：一堆数据构成的数组 </span></span><br><span class="line"><span class="comment">name:文件名</span></span><br><span class="line"><span class="comment">options：设置一些属性，type属性、lastModified</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">File对象属性</span></span><br><span class="line"><span class="comment">name：文件名</span></span><br><span class="line"><span class="comment">size：文件大小</span></span><br><span class="line"><span class="comment">lastModified ：最后修改时间（时间戳）</span></span><br><span class="line"><span class="comment">lastModifiedDate:最后修改时间Data对象</span></span><br><span class="line"><span class="comment">type：MIME类型</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">File对象方法</span></span><br><span class="line"><span class="comment">继承自Blob的slice方法</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">Blob.slice(start, end, contentType)</span><br></pre></td></tr></table></figure>

<h3 id="ArrayBuffer"><a href="#ArrayBuffer" class="headerlink" title="ArrayBuffer"></a>ArrayBuffer</h3><p>ArrayBuffer是内存上一段二进制数据，我们可以借助工具TypeArray、DataView对它进行读写。</p>
<p>Blob与ArrayBuffer的关系：</p>
<p>1、ArrayBuffer是底层二进制数据，可以借助工具进行读写，而Blob是对底层二进制数据的封装，我们拿到的就是一个整体，能够读取他的大小，类型，但是不能看到细节。</p>
<p>2、Blob可以接受一个ArrayBuffer作为参数生成一个Blob对象，此行为就相当于对ArrayBuffer数据做一个封装，之后就是以整体的形式展现了Blob作为一个整体文件，适合用于传输；而只有需要关注细节（比如要修改某一段数据时），才需要用到ArrayBuff。</p>
<h3 id="Base64"><a href="#Base64" class="headerlink" title="Base64"></a>Base64</h3><p>有些网络传送渠道并不支持所有的字节，例如传统的邮件只支持可见字符的传送，像ASCII码的控制字符就不能通过邮件传送。这样用途就受到了很大的限制，比如图片二进制流的每个字节不可能全部是可见字符，所以就传送不了。</p>
<p>最好的方法就是在不改变传统协议的情况下，做一种扩展方案来支持二进制文件的传送。把不可打印的字符也能用可打印字符来表示，问题就解决了。Base64编码应运而生，Base64就是一种基于64个可打印字符来表示二进制数据的表示方法。</p>
<h2 id="文件间相互转换"><a href="#文件间相互转换" class="headerlink" title="文件间相互转换"></a>文件间相互转换</h2><h3 id="File与Blob"><a href="#File与Blob" class="headerlink" title="File与Blob"></a>File与Blob</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// File文件转换为Blob对象;直接用new Blob新建对象即可，传入参数可为file数组。</span></span><br><span class="line"><span class="keyword">let</span> aBlob = <span class="keyword">new</span> Blob([file], &#123;<span class="attr">type</span>: file.type&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//Blob转换为File；用new window.File新建即可，传入参数可谓blob；</span></span><br><span class="line"><span class="keyword">let</span> files = <span class="keyword">new</span> <span class="built_in">window</span>.File([<span class="keyword">this</span>.blob], file.name, &#123;<span class="attr">type</span>: file.type&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="File与Blob转换成base64"><a href="#File与Blob转换成base64" class="headerlink" title="File与Blob转换成base64"></a>File与Blob转换成base64</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//File/Blob文件转换为base64，利用FileReader对象来进行处理blob，可获取base64格式的结果。</span></span><br><span class="line"><span class="comment">// 原理：利用fileReader的readAsDataURL，将blob转为base64</span></span><br><span class="line"><span class="keyword">const</span> blobToBase64 = <span class="function">(<span class="params">blob</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">const</span> fileReader = <span class="keyword">new</span> FileReader();</span><br><span class="line">      fileReader.onload = <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">        resolve(e.target.result);</span><br><span class="line">      &#125;;</span><br><span class="line">      <span class="comment">// readAsDataURL</span></span><br><span class="line">      fileReader.readAsDataURL(blob);</span><br><span class="line">      fileReader.onerror = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        reject(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'文件流异常'</span>));</span><br><span class="line">      &#125;;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//可以如下调用，这种文件的转化，最好使用promise来写成异步的形式,毕竟文件的转换比较耗时</span></span><br><span class="line"><span class="keyword">this</span>.blobToBase64(blob).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 转化后的base64</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'base64'</span>, res)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="图片url转base64"><a href="#图片url转base64" class="headerlink" title="图片url转base64"></a>图片url转base64</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 原理： 利用canvas.toDataURL的API转化成base64</span></span><br><span class="line"><span class="keyword">const</span> urlToBase64 = <span class="function">(<span class="params">url</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span> (<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> image = <span class="keyword">new</span> Image();</span><br><span class="line">        image.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">          <span class="keyword">let</span> canvas = <span class="built_in">document</span>.createElement(<span class="string">'canvas'</span>);</span><br><span class="line">          canvas.width = <span class="keyword">this</span>.naturalWidth;</span><br><span class="line">          canvas.height = <span class="keyword">this</span>.naturalHeight;</span><br><span class="line">          <span class="comment">// 将图片插入画布并开始绘制</span></span><br><span class="line">          canvas.getContext(<span class="string">'2d'</span>).drawImage(image, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">          <span class="comment">// result</span></span><br><span class="line">          <span class="keyword">let</span> result = canvas.toDataURL(<span class="string">'image/png'</span>)</span><br><span class="line">          resolve(result);</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// CORS 策略，会存在跨域问题https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror</span></span><br><span class="line">        image.setAttribute(<span class="string">"crossOrigin"</span>,<span class="string">'Anonymous'</span>);</span><br><span class="line">        image.src = url;</span><br><span class="line">        <span class="comment">// 图片加载失败的错误处理</span></span><br><span class="line">        image.onerror = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">          reject(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'图片流异常'</span>));</span><br><span class="line">      &#125;;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h3 id="base64转blob与file"><a href="#base64转blob与file" class="headerlink" title="base64转blob与file"></a>base64转blob与file</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//base64 转 blob</span></span><br><span class="line"><span class="comment">// 原理：利用URL.createObjectURL为blob对象创建临时的URL</span></span><br><span class="line"><span class="keyword">const</span> base64ToBlob  = <span class="function">(<span class="params">&#123;b64data = <span class="string">''</span>, contentType = <span class="string">''</span>, sliceSize = <span class="number">512</span>&#125; = &#123;&#125;</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 使用 atob() 方法将数据解码</span></span><br><span class="line">      <span class="keyword">let</span> byteCharacters = atob(b64data);</span><br><span class="line">      <span class="keyword">let</span> byteArrays = [];</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> offset = <span class="number">0</span>; offset &lt; byteCharacters.length; offset += sliceSize) &#123;</span><br><span class="line">        <span class="keyword">let</span> slice = byteCharacters.slice(offset, offset + sliceSize);</span><br><span class="line">        <span class="keyword">let</span> byteNumbers = [];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; slice.length; i++) &#123;</span><br><span class="line">            byteNumbers.push(slice.charCodeAt(i));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 8 位无符号整数值的类型化数组。内容将初始化为 0。</span></span><br><span class="line">        <span class="comment">// 如果无法分配请求数目的字节，则将引发异常。</span></span><br><span class="line">        byteArrays.push(<span class="keyword">new</span> <span class="built_in">Uint8Array</span>(byteNumbers));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">let</span> result = <span class="keyword">new</span> Blob(byteArrays, &#123;</span><br><span class="line">        type: contentType</span><br><span class="line">      &#125;)</span><br><span class="line">      result = <span class="built_in">Object</span>.assign(result,&#123;</span><br><span class="line">        <span class="comment">// jartto: 这里一定要处理一下 URL.createObjectURL</span></span><br><span class="line">        preview: URL.createObjectURL(result),</span><br><span class="line">        name: <span class="string">`图片示例.png`</span></span><br><span class="line">      &#125;);</span><br><span class="line">      resolve(result)</span><br><span class="line">    &#125;)</span><br><span class="line"> &#125;;</span><br><span class="line"><span class="keyword">const</span> dataURLtoBlob = <span class="function"><span class="keyword">function</span> (<span class="params">dataurl</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> arr = dataurl.split(<span class="string">','</span>);</span><br><span class="line">    <span class="comment">//注意base64的最后面中括号和引号是不转译的</span></span><br><span class="line">    <span class="keyword">var</span> _arr = arr[<span class="number">1</span>].substring(<span class="number">0</span>,arr[<span class="number">1</span>].length<span class="number">-2</span>);</span><br><span class="line">    <span class="keyword">var</span> mime = arr[<span class="number">0</span>].match(<span class="regexp">/:(.*?);/</span>)[<span class="number">1</span>],</span><br><span class="line">        bstr =atob(_arr),<span class="comment">//获得解码后字符串</span></span><br><span class="line">        n = bstr.length,</span><br><span class="line">        u8arr = <span class="keyword">new</span> <span class="built_in">Uint8Array</span>(n);</span><br><span class="line">    <span class="comment">//正新建一个8位的整数类型数组，用于存放ASCII码编码的字符串</span></span><br><span class="line">    <span class="keyword">while</span> (n--) &#123;</span><br><span class="line">        u8arr[n] = bstr.charCodeAt(n);<span class="comment">//转换编码后。用charCodeAts找到Unicode编码</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Blob([u8arr], &#123;</span><br><span class="line">        type: mime</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">js中有两个方法专门用来处理base64编解码</span></span><br><span class="line"><span class="comment">window.btoa() 和 window.atob()</span></span><br><span class="line"><span class="comment">btoa() 方法使用base-64 编码字符串</span></span><br><span class="line"><span class="comment">atob() 方法用于解码使用 base-64 编码的字符串。</span></span><br><span class="line"><span class="comment">注意⚠️：这两个方法都是返回字符串 atob()方法解码后返回的是unicode编码的字符串 不是二进制对象</span></span><br><span class="line"><span class="comment">上面该函数将base64编码转换成blob对象后，后续再利用</span></span><br><span class="line"><span class="comment">window.url.createObjectURL来进行构建DOM对象。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">let</span> newBlob = <span class="built_in">window</span>.URL.createObjectURL(dataURLtoBlob(base64));</span><br></pre></td></tr></table></figure>

<h3 id="FileReader"><a href="#FileReader" class="headerlink" title="FileReader"></a>FileReader</h3><p>通过fileReader可以将Blob、File读取为不同的格式。</p>
<p>FileReader.readAsDataURL(blob)将二进制数据读取并编码为Base64格式</p>
<p>FileReader.readAsText(blob)就是将二进制数据读取并编码为字符串形式</p>
<h3 id="FormData"><a href="#FormData" class="headerlink" title="FormData"></a>FormData</h3><p>使用FormData我们可以异步上传一个二进制文件，而这个二进制文件，就是我们上面讲的Blob对象。</p>

    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/07/14/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E5%9B%BE%E7%89%87%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%A4%84%E7%90%86/" title="图片上传问题">http://example.com/2021/07/14/学校项目应用/图片文件上传处理/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/" rel="tag"># 学校项目应用</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/07/10/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/%E4%BB%8ECORS%E5%BC%80%E5%A7%8B%E7%AE%80%E8%BF%B0HTTP%E5%A4%B4/" rel="prev" title="从CORS开始的HTTP首部概述">
      <i class="fa fa-chevron-left"></i> 从CORS开始的HTTP首部概述
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/07/16/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E5%89%8D%E7%AB%AF%E5%AE%89%E5%85%A8%E7%9B%B8%E5%85%B3/" rel="next" title="前端安全概论">
      前端安全概论 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#图片上传问题"><span class="nav-number">1.</span> <span class="nav-text">图片上传问题</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#文件格式类型"><span class="nav-number">1.1.</span> <span class="nav-text">文件格式类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Blob"><span class="nav-number">1.1.1.</span> <span class="nav-text">Blob</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#File"><span class="nav-number">1.1.2.</span> <span class="nav-text">File</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ArrayBuffer"><span class="nav-number">1.1.3.</span> <span class="nav-text">ArrayBuffer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Base64"><span class="nav-number">1.1.4.</span> <span class="nav-text">Base64</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#文件间相互转换"><span class="nav-number">1.2.</span> <span class="nav-text">文件间相互转换</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#File与Blob"><span class="nav-number">1.2.1.</span> <span class="nav-text">File与Blob</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#File与Blob转换成base64"><span class="nav-number">1.2.2.</span> <span class="nav-text">File与Blob转换成base64</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#图片url转base64"><span class="nav-number">1.2.3.</span> <span class="nav-text">图片url转base64</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#base64转blob与file"><span class="nav-number">1.2.4.</span> <span class="nav-text">base64转blob与file</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#FileReader"><span class="nav-number">1.2.5.</span> <span class="nav-text">FileReader</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#FormData"><span class="nav-number">1.2.6.</span> <span class="nav-text">FormData</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

